package com.luban.server.lbtransaction.util;

import java.util.Collections;
import java.util.HashMap;
import java.util.Map;

public class MyThreadLocal<T> {

    private Map<Thread, T> container = Collections.synchronizedMap(new HashMap<Thread, T>());

    protected T initialValue() {
        return null;
    }
    private T initilization(Thread currentThread ) {
        T t = initialValue();
        container.put(currentThread, t);
        return t;
    }

    public T get() {
        Thread currentThread = Thread.currentThread();
        T t = container.get(currentThread);
        if (t != null) {
            return t;
        }
        return initilization(currentThread);
    }

    public void remove() {
        Thread currentThread = Thread.currentThread();
        if (this.container.containsKey(currentThread)) {
            this.container.remove(currentThread);
        }
    }

    public void set(T t) {
        Thread currentThread = Thread.currentThread();
        this.container.put(currentThread, t);
    }
}
